package org.example.utils;

import com.sun.corba.se.spi.orbutil.threadpool.ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhanghao
 * @create 2024-01-22 13:40
 */
public class ExecutorConfig {

    private static int maxPoolSize = Runtime.getRuntime().availableProcessors();
    private volatile static ExecutorService executorService;

    public static ExecutorService getThreadPool(){
        if(executorService == null){
            synchronized (ExecutorConfig.class){
                if(executorService == null){
                    executorService = newThreadPool();
                }
            }
        }
        return executorService;
    }

    private static ExecutorService newThreadPool(){
        int queueSize = 500;
        int corePool = Math.min(5,maxPoolSize);
        return new ThreadPoolExecutor(corePool,
                maxPoolSize,
                1000L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(queueSize),
                new ThreadPoolExecutor.AbortPolicy());

    }

    private ExecutorConfig(){}
}
